package com.tengju.data.application.sync;

import com.tengju.data.application.shared.ApplicationException;
import com.tengju.data.domain.model.clickhouse.crm.ActivityCrowdRepository;
import com.tengju.data.domain.model.cqrs.DataActivitySubjectType;
import com.tengju.data.domain.model.service.CrowdExternalService;
import com.tengju.data.domain.shared.CastUtil;
import com.tengju.motivation.domain.model.activity.Activity;
import com.tengju.motivation.domain.model.activity.ActivityRepository;
import com.tengju.motivation.domain.model.activity.ActivityTargetType;
import com.tengju.motivation.domain.model.activity.UserLevel;
import com.tengju.user.domain.shared.BizException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenhang
 * @Date 2022/1/8
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ActivitySyncApplicationService {

    private final ActivityRepository activityRepository;
    private final CrowdExternalService crowdExternalService;
    private final ActivityCrowdRepository activityCrowdRepository;

    @Value("${crowd.sync.page.size}")
    private Integer crowdSyncPageSize;


    public void syncActivityCrowd(Activity activity) {
        if (activity == null) {
            throw ApplicationException.error("活动不存在");
        }
        if (activity.getExtraInfo() == null) {
            throw ApplicationException.error("活动信息不完整");
        }
        Long activityId = activity.getActivityId().getValue();
        Activity.ActivityExtraInfo extraInfo = activity.getExtraInfo();
        Long crowdId = extraInfo.getIntentionCrowdId() != null ? extraInfo.getIntentionCrowdId().getValue() : 0L;
        Long version = System.currentTimeMillis();
        LocalDateTime insertTime = LocalDateTime.now();
        for (int i = 0; i < 10000; i++) {
            List<Long> idCodeList = crowdExternalService.listCrowdUser(crowdId,i + 1,crowdSyncPageSize,version);
            if (CollectionUtils.isEmpty(idCodeList)) {
                break;
            }
            log.info("人群数据导入clickhouse：{}",crowdId);
            activityCrowdRepository.saveCrowdUser(activityId,crowdId,insertTime,idCodeList);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw ApplicationException.error("活动人群同步中断" + activityId);
            }
        }
        log.info("开始同步人群detail，{}",activityId);
        syncActivityCrowdDetail(activity);
    }

    public void syncActivityCrowdDetail(Activity activity) {
        if (activity == null) {
            return;
        }
        if (activity.getExtraInfo() == null) {
            throw ApplicationException.error("活动信息不完整");
        }
        Activity.ActivityExtraInfo extraInfo = activity.getExtraInfo();
        Long crowdId = extraInfo.getIntentionCrowdId() != null ? extraInfo.getIntentionCrowdId().getValue() : 0L;
        Long activityId = activity.getActivityId().getValue();
        List<Integer> limitVtnLevels = new ArrayList<>();
        // 用户增长活动
        if (ActivityTargetType.GROWTH.equals(extraInfo.getTargetType())) {
            //受众等级
            UserLevel targetGrownUserLevel = extraInfo.getTargetGrownUserLevel();
            if (targetGrownUserLevel == null) {
                throw new BizException("活动受众等级缺失：" + activity.getActivityId().getValue());
            }
            limitVtnLevels = Arrays.stream(UserLevel.values())
                    .filter(v -> v.isLower(targetGrownUserLevel))
                    .map(v -> v.getVal().intValue())
                    .collect(Collectors.toList());


            // 销售活动
        } else if (ActivityTargetType.SALE.equals(extraInfo.getTargetType())) {
            //受众等级
            if (CollectionUtils.isEmpty(extraInfo.getLimitCustomerLevel())) {
                throw new BizException("活动受众等级缺失：" + activity.getActivityId().getValue());
            }
            if (!CollectionUtils.isEmpty(extraInfo.getLimitCustomerLevel())) {
                limitVtnLevels = extraInfo.getLimitCustomerLevel().stream()
                        .map(v -> v.getVal().intValue())
                        .collect(Collectors.toList());
            }
        }
        if (CollectionUtils.isEmpty(limitVtnLevels)) {
            throw new BizException("受众人群为空！" + activityId);
        }
        log.info("同步人群detail，{}",activityId);
        activityCrowdRepository.syncActivityCrowdDetail(activityId,crowdId,limitVtnLevels);
    }

    public void syncActivityCrowdDetailFromBehavior(Activity activity) {
        if (activity == null) {
            return;
        }
        if (activity.getExtraInfo() == null) {
            throw ApplicationException.error("活动信息不完整");
        }
        Activity.ActivityExtraInfo extraInfo = activity.getExtraInfo();
        Long crowdId = extraInfo.getIntentionCrowdId() != null ? extraInfo.getIntentionCrowdId().getValue() : 0L;
        Long activityId = activity.getActivityId().getValue();
        activityCrowdRepository.syncActivityCrowdDetailFromBehavior(activityId,crowdId);
    }


}
